package com.yiqi.lottery.feature.lottery.view;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.suozhang.framework.component.recyclerview.DividerItemDecoration;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.utils.logger.Logger;
import com.yiqi.lottery.R;
import com.yiqi.lottery.common.util.DateTool;
import com.yiqi.lottery.entity.bo.*;
import com.yiqi.lottery.entity.enums.DaletouType;
import com.yiqi.lottery.feature.home.view.PayActivity;
import com.yiqi.lottery.feature.lottery.contract.LottoContract;
import com.yiqi.lottery.feature.lottery.data.ConfirmLotteryOpe;
import com.yiqi.lottery.feature.lottery.data.LotteryData;
import com.yiqi.lottery.feature.lottery.dependencies.lotto.DaggerLottoComponent;
import com.yiqi.lottery.feature.lottery.dependencies.lotto.LottoPresenterModule;
import com.yiqi.lottery.feature.lottery.view.adapter.DaletouAdapter;
import com.yiqi.lottery.framework.DataServer;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;

public class ConfirmBettingActivity extends BaseActivity implements Toolbar.OnMenuItemClickListener,
        BaseQuickAdapter.OnItemLongClickListener, LottoContract.View, CompoundButton.OnCheckedChangeListener {
    @Inject
    LottoContract.Presenter mPresenter;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.rv_confrim)
    RecyclerView mRvConfrim;
    @BindView(R.id.cbx_lottery_daletou_agree)
    CheckBox mCbxLotteryDaletouAgree;
    @BindView(R.id.tv_lottery_daletou_beishu_jian)
    EditText mTvLotteryDaletouBeishu;
    @BindView(R.id.tv_lottery_current_qi)
    TextView mTvCurrentQi;
    @BindView(R.id.tv_lottery_current_date)
    TextView mTvCurrentDate;
    @BindView(R.id.tv_lottery_daletou_qishu_jian)
    EditText mTvLotteryDaletouQishu;
    @BindView(R.id.cbx_lottery_daletou_zhuijia)
    CheckBox mCbxLotteryDaletouZhuijia;
    @BindView(R.id.tv_lottery_daletou_prize)
    TextView mTvLotteryDaletouPrize;
    @BindView(R.id.view_bottom)
    RelativeLayout mViewBottom;
    private DaletouAdapter mAdapter;
    List<SelectItem> mSelectItems;
    LuckyHistoryBo mLuckyCurrent = null;
    List<ConfirmLotteryBo> mConfirmLotteryBos;
    private String mIssues;
    private int mBeishu = 1;
    private int mQishu = 1;

    private int mPrize = 2;

    private int is_charsing = 2;//是否追号
    private int zhushu;

    private int total_amount;
    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_confirm_betting;
    }

    @Override
    protected void initInjector() {
        DaggerLottoComponent.builder().lottoPresenterModule(new LottoPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        mToolbar.inflateMenu(R.menu.menu_find_circle_answer);
        initToolBar(mToolbar, "确认投注", true, true);
        mToolbar.setOnMenuItemClickListener(this);
        initAdapter();
    }


    @Override
    protected void initData() {
        mPresenter.getCurrentQi();
        mTvLotteryDaletouBeishu.setText("" + mBeishu);
        mTvLotteryDaletouQishu.setText("" + mQishu);
        updateBeishu(mBeishu, mPrize);
    }


    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_cieclr_write:
                break;
        }
        return true;
    }

    @Override
    protected void initEvent() {
        mCbxLotteryDaletouZhuijia.setOnCheckedChangeListener(this);
        mTvLotteryDaletouQishu.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    if (!TextUtils.isEmpty(s.toString())) {
                        int num = Integer.valueOf(s.toString());
                            mQishu = num;
                            setPrizeText();
                    }
                } catch (Exception e) {

                }

            }
        });
        mTvLotteryDaletouBeishu.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    if (!TextUtils.isEmpty(s.toString())) {
                        int num = Integer.valueOf(s.toString());
                            mBeishu = num;
                            updateBeishu(mBeishu, mPrize);
                            setPrizeText();
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    private void initAdapter() {

        mAdapter = new DaletouAdapter();
//        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
//        mAdapter.isFirstOnly(false);
        mRvConfrim.setLayoutManager(new LinearLayoutManager(this));
        mRvConfrim.addItemDecoration(new DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(2));
        mAdapter.bindToRecyclerView(mRvConfrim);
        mAdapter.setOnItemLongClickListener(this);
        mConfirmLotteryBos = ConfirmLotteryOpe.queryAll(this);
        if (mConfirmLotteryBos != null) {
            mAdapter.setNewData(mConfirmLotteryBos);
        }
        setPrizeText();
    }

    @OnClick({R.id.btn_daletou_confirm_random, R.id.btn_daletou_confirm_manual})
    public void onView3Clicked(View view) {
        switch (view.getId()) {
            case R.id.btn_daletou_confirm_random:
                addNormalData();
                setPrizeText();
                break;
            case R.id.btn_daletou_confirm_manual:
                finish();
                break;
        }
    }

    public void addNormalData() {
        mSelectItems = new ArrayList<>();
        List<LuckySection> luckySections = DataServer.getNormalRandomData();
        for (int i = 0; i < luckySections.size(); i++) {
            SelectItem selectItem = luckySections.get(i).t;
            if (selectItem != null && selectItem.isCheck()) {
                mSelectItems.add(selectItem);
            }
        }
        if (mSelectItems != null && mSelectItems.size() >= 7) {
            ConfirmLotteryBo confirmLotteryBo = new ConfirmLotteryBo();
            confirmLotteryBo.setName(LotteryData.getLottery(mSelectItems, false)[0]);
            confirmLotteryBo.setHouName(LotteryData.getLottery(mSelectItems, false)[1]);
            confirmLotteryBo.setCount(1);
            confirmLotteryBo.setPrize(mBeishu * mPrize * mQishu);
            confirmLotteryBo.setType(DaletouType.DANSHI.getIndex());
            ConfirmLotteryOpe.insertData(this, confirmLotteryBo);
            mAdapter.addData(0, confirmLotteryBo);
            mRvConfrim.smoothScrollToPosition(0);
        }
    }

    @Override
    public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
        tipClick(mAdapter.getData().get(position).getId(), position, false);
        return false;
    }


    public void tipClick(long id, int position, boolean isClear) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("温馨提示");
        if (isClear) {
            builder.setMessage("是否清除全部记录？");
        } else {
            builder.setMessage("是否删除此条记录？");
        }
        builder.setCancelable(true);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (isClear) {
                    ConfirmLotteryOpe.deleteAllData(ConfirmBettingActivity.this);
                    if (mAdapter != null) {
                        mAdapter.setNewData(null);
                    }
                } else {
                    ConfirmLotteryOpe.deleteByKeyData(ConfirmBettingActivity.this, id);
                    mAdapter.remove(position);
                    dialog.dismiss();
                }
                mAdapter.notifyDataSetChanged();
                setPrizeText();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }


    @OnClick({R.id.btn_lottery_daletou_beishu_jian, R.id.btn_lottery_daletou_beishu_jia, R.id.btn_lottery_daletou_qishu_jian, R.id.btn_lottery_daletou_qishu_jia, R.id.btn_lottery_lucky_clear_data, R.id.btn_lottery_daletou_buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_lottery_daletou_beishu_jian:

                if (mBeishu > 1) {
                    mBeishu--;
                    updateBeishu(mBeishu, mPrize);
                }
                break;
            case R.id.btn_lottery_daletou_beishu_jia:
                mBeishu++;
                updateBeishu(mBeishu, mPrize);
                break;
            case R.id.btn_lottery_daletou_qishu_jian:
                if (mQishu > 1) {
                    mQishu--;
                }
                break;
            case R.id.btn_lottery_daletou_qishu_jia:
                mQishu++;
                break;
            case R.id.btn_lottery_lucky_clear_data:
                tipClick(0, 0, true);
                break;
            case R.id.btn_lottery_daletou_buy:
                mConfirmLotteryBos = mAdapter.getData();
                if (mConfirmLotteryBos != null && mConfirmLotteryBos.size() > 0) {
                } else {
                    T.showShort("请至少选择一注！");
                    return;
                }


                Intent intent = new Intent(this, PayActivity.class);
                intent.putExtra("order_type",1 );
                intent.putExtra("data", LotteryData.getLottoOrder(mConfirmLotteryBos));
                intent.putExtra("multiple", mBeishu);
                intent.putExtra("is_charsing",is_charsing);
                intent.putExtra("charsing_num",mQishu);
                intent.putExtra("issue", mIssues);
                intent.putExtra("mut_num", zhushu);
                intent.putExtra("total_amount", total_amount);
                startActivity(intent);
                break;
        }

        mAdapter.notifyDataSetChanged();
        mTvLotteryDaletouBeishu.setText("" + mBeishu);
        mTvLotteryDaletouQishu.setText("" + mQishu);
        setPrizeText();
    }

    /***
     * 更新列表倍数
     * */
    private void updateBeishu(int beishu, int prize) {
        mConfirmLotteryBos = mAdapter.getData();
        for (int i = 0; i < mConfirmLotteryBos.size(); i++) {
            mConfirmLotteryBos.get(i).setPrize(beishu * prize);
        }

        ConfirmLotteryOpe.deleteAllData(this);
        ConfirmLotteryOpe.insertData(this, mConfirmLotteryBos);
    }


    @Override
    public void showCurrentSuccess(LuckyHistoryBo luckyHistoryBo) {
        mIssues = luckyHistoryBo.getIssue();
        mTvCurrentQi.setText("第" + luckyHistoryBo.getIssue() + "期");
        mTvCurrentDate.setText(DateTool.dateMinus10(luckyHistoryBo.getStopDate()) + "截至投注");
    }

    @Override
    public void showCurrentError(String ex) {

    }

    @Override
    public void showCreateOrderSuccess(String luckyHistoryBo) {
        T.showShort("订单创建成功！");
    }

    @Override
    public void showCreateOrderError(String ex) {
        T.showShort(ex);
    }

    @Override
    public void showLotteryHistorySuccess(List<LotteryHistoryBo> resultBos) {

    }

    @Override
    public void showLotteryHistoryError(String error) {

    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        is_charsing = isChecked ? 1 : 2;
        if (isChecked) {
            mPrize = 3;
        } else {
            mPrize = 2;
        }
        setPrizeText();
        updateBeishu(mBeishu, mPrize);
        mAdapter.notifyDataSetChanged();
    }

    private void setPrizeText() {
        zhushu = 0;
        for (int i = 0; i < mAdapter.getData().size(); i++) {
            zhushu += mAdapter.getData().get(i).getCount();
        }
        total_amount=zhushu * mBeishu * mQishu * mPrize;

        mTvLotteryDaletouPrize.setText(Html.fromHtml(zhushu + "<font color=\"#333333\">注</font>" + total_amount + "<font color=\"#333333\">元</font>"));
    }
}

